#import "RNItemCell.h"
#import "RNConstants.h"
#import "RNItem.h"
#import "NSBezierPath+MCAdditions.h"
#import "NSShadow+MCAdditions.h"
#import "RNCategory.h"

NSUInteger const RNItemCellMinimumTitleWidth = 30;
static NSColor *backgroundColor, *backgroundColorHighlighted, *backgroundColorHighlightedInactive;

@implementation RNItemCell

@synthesize heartCell = heartCell_;
@synthesize favorite = favorite_;
@synthesize category = category_;
@synthesize titleAttributes = titleAttributes_;
@synthesize listItems = listItems_;

+(void)initialize {
    backgroundColor = [NSColor colorWithCalibratedWhite:0.95f alpha:1.0f];
    backgroundColorHighlighted = [NSColor colorWithCalibratedRed:0.851 green:0.890 blue:0.957 alpha:1.000];
    backgroundColorHighlightedInactive = [NSColor colorWithCalibratedWhite:0.831 alpha:1.0];
}

+ (BOOL)prefersTrackingUntilMouseUp {
    return YES;
}

-(id)initTextCell:(NSString *)theString {
    if (!(self = [super initTextCell:theString]))
        return nil;
        
    [self setLineBreakMode:NSLineBreakByTruncatingTail];
    [self setFont:[NSFont systemFontOfSize:12.0f]];
    
    NSButtonCell *heartButtonCell = [[NSButtonCell alloc] initImageCell:[NSImage imageNamed:@"sourceList_favorites.png"]];
    [heartButtonCell setBordered:NO];
    [heartButtonCell setImageScaling:NSImageScaleProportionallyDown];
    [self setHeartCell:heartButtonCell];
    
    return self;
}

-(id)copyWithZone:(NSZone *)zone {
    RNItemCell *copy = [super copyWithZone:zone];
    
    copy->heartCell_ = nil;
    [copy setHeartCell:[[self heartCell] copy]];
    
    return copy;
}

-(NSArray *)keys {
    return [NSArray arrayWithObjects:@"title", @"favorite", nil];
}

-(id)objectValue {
    return [self dictionaryWithValuesForKeys:[self keys]];
}

-(void)setObjectValue:(id)obj {
    if (![obj isKindOfClass:[NSDictionary class]])
        return;
    [self setValuesForKeysWithDictionary:obj];
    [super setObjectValue:[obj valueForKey:RNTitleKey]];
}

-(NSDictionary *)titleAttributes {
    if (!titleAttributes_) {
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        [attributes setValue:[NSFont controlContentFontOfSize:12.0f] forKey:NSFontAttributeName];
        [attributes setValue:[NSColor blackColor] forKey:NSForegroundColorAttributeName];
        titleAttributes_ = attributes;
    }
    return titleAttributes_;
}


#pragma mark -
#pragma mark Cell Behavior

-(BOOL)isSelectable {
    return YES;
}

-(BOOL)isEditable {
	return YES;
}


#pragma mark -
#pragma mark Editing

-(void)editWithFrame:(NSRect)aRect inView:(NSView *)controlView editor:(NSText *)textObj delegate:(id)anObject event:(NSEvent *)theEvent {
	[self endEditing:textObj];
    [NSApp sendAction:@selector(editSelectedItem:) to:nil from:self];    
}

-(void)selectWithFrame:(NSRect)aRect inView:(NSView *)controlView editor:(NSText *)textObj delegate:(id)anObject start:(NSInteger)selStart length:(NSInteger)selLength {
	[self endEditing:textObj];
    [NSApp sendAction:@selector(editSelectedItem:) to:nil from:self];    
}


#pragma mark -
#pragma mark Drawing

-(void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {
    NSRect insetFrame = NSInsetRect(cellFrame, RNDetailViewBorderPadding, 0.0f);
    NSBezierPath *boundingPath = [NSBezierPath bezierPathWithRoundedRect:insetFrame xRadius:RNDetailViewCellCornerRadius yRadius:RNDetailViewCellCornerRadius];

    // Draw background
    NSColor *highlightedColor = [[controlView window] firstResponder] == controlView && [NSApp isActive] ? backgroundColorHighlighted : backgroundColorHighlightedInactive;
    NSColor *currentBackgroundColor = [self isHighlighted] ? highlightedColor : backgroundColor;
    [currentBackgroundColor setFill];
    [boundingPath fill];
    
    // Draw favorite icon
    if ([[self favorite] boolValue]) 
        [[self heartCell] drawWithFrame:[self favoriteRectForBounds:cellFrame] inView:controlView];
    
    NSAttributedString *title = [[NSAttributedString alloc] initWithString:[self stringValue] attributes:[self titleAttributes]];
    [title drawInRect:[self titleRectForBounds:insetFrame]];
}

-(NSRect)titleRectForBounds:(NSRect)cellFrame {
    NSRect titleFrame = cellFrame;
    CGFloat widthAdjustment = 0;
    if ([[self favorite] boolValue])
        widthAdjustment += RNDetailCellFavoriteWidth + RNGenericCellElementPadding;
    titleFrame.origin.x += RNGenericCellEndPadding;
    titleFrame.size.width -= RNGenericCellEndPadding + (widthAdjustment == 0 ? RNGenericCellEndPadding : widthAdjustment);
    titleFrame.size.height = [[self attributedStringValue] size].height;
    titleFrame.origin.y += NSMidY(cellFrame) - NSMidY(titleFrame);
    return titleFrame;
}

-(NSRect)favoriteRectForBounds:(NSRect)cellFrame {
    if (![[self favorite] boolValue])
        return NSZeroRect;
    return NSMakeRect((NSMaxX(cellFrame) - RNDetailCellFavoriteWidth - RNGenericCellEndPadding), NSMinY(cellFrame), RNDetailCellFavoriteWidth, NSHeight(cellFrame));
}

- (NSColor *)highlightColorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {
    return nil;
}

@end
